package com.q.springboot.framework.advice;

import com.alibaba.fastjson.JSON;
import com.q.springboot.framework.annotation.ResponseResult;
import com.q.springboot.framework.exception.CustomException;
import com.q.springboot.framework.util.Result;
import com.q.springboot.framework.enums.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ：qmf
 * @date ：Created in 2020/6/17 19:33
 * @description：
 * @modified By：
 */
@Slf4j
@RestControllerAdvice
public class ResponseResultAdvice implements ResponseBodyAdvice<Object> {

    public static final String RESPONSE_RESULT_ANN = "RESPONSE_RESULT_ANN";

    //是否请求 包含了 包装注解标记，没有直接返回，不需要包装返回体
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        log.info("进入ControllerAdvice--supports....");
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();
        //判断请求是否有包装标记
        ResponseResult responseResult = (ResponseResult) request.getAttribute(RESPONSE_RESULT_ANN);
        return responseResult != null;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        log.info("进入返回体，重写格式中....");
        if (body instanceof CustomException) {
            CustomException exception = (CustomException) body;
            return Result.failure(ResultCode.RESPONSE_ERROR, null);
        }
        if (body instanceof Result) {
            return body;
        }
        //当返回类型是String时，用的是StringHttpMessageConverter转换器，无法转换为Json格式
        //必须在方法体上标注RequestMapping(produces = "application/json; charset=UTF-8")
        if (body instanceof String) {
            String str = JSON.toJSONString(Result.success(body));
            return str;
        }
        return Result.success(body);
    }
}
